package top.yangguangmc.sunshine_anticheat;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.jetbrains.annotations.NotNull;
import top.yangguangmc.sunshine_anticheat.utils.Utils;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

import static top.yangguangmc.sunshine_anticheat.utils.Builtin.ssac;

public class AlertManager implements Listener {
    public static final String PERMISSION = "sunshineac.alert";
    private final Set<UUID> alertEnabledPlayers = new HashSet<>();

    AlertManager() {
        Bukkit.getPluginManager().registerEvents(this, ssac);
    }

    public void send(String message) {
        String s = SunshineAntiCheat.getInstance().getPrefix().concat(message);
        s = Utils.preprocessString(s);
        Bukkit.getConsoleSender().sendMessage(s);
        for (Player player : Bukkit.getOnlinePlayers())
            if (player.hasPermission(PERMISSION) && alertEnabledPlayers.contains(player.getUniqueId()))
                player.sendMessage(s);
    }

    public void toggleAlert(@NotNull Player player) {
        UUID uuid = player.getUniqueId();
        if (alertEnabledPlayers.contains(uuid))
            alertEnabledPlayers.remove(uuid);
        else alertEnabledPlayers.add(uuid);
        player.sendMessage(ssac.getPrefix() + "Your alerts are " + (alertEnabledPlayers.contains(uuid) ? "enabled." : "disabled."));
    }

    public boolean isAlertEnabled(@NotNull Player player) {
        return alertEnabledPlayers.contains(player.getUniqueId());
    }

    @EventHandler
    public void onJoin(PlayerJoinEvent event) {
        if (event.getPlayer().hasPermission(PERMISSION)) {
            alertEnabledPlayers.add(event.getPlayer().getUniqueId());
        }
    }

    @EventHandler
    public void onQuit(PlayerQuitEvent event) {
        alertEnabledPlayers.remove(event.getPlayer().getUniqueId());
    }
}
